<?php

namespace app\api\controller;

use app\common\controller\Api;
use think\Db;

/**
 * 首页接口
 */
class Work extends Api
{
    protected $noNeedLogin = ['getNotice'];
    protected $noNeedRight = ['*'];

    /**
     * 首页
     *
     */
    public function index()
    {
        $this->success('请求成功');
    }

    /**
     * @return void
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * 获取产品信息
     */
    public function productList(){
        $list = Db::name("product")->where('deletetime',null)->field("id,code")->order("id desc")->select();
        $this->success('',$list);
    }

    /**
     * @return void
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * 通过产品ID获取产品名称和工厂名称
     */
    public function getDate(){
       // $code = $this->request->post('code');//产品序列号
        $ids = $this->request->post("id");//产品ID
        $product = Db::name("product")->where(['id'=>$ids])->find();
        $factory = Db::name("factory")->where(['id'=>$product['factory_id']])->find();
        $productname = Db::name("productname")->where(['id'=>$product['productname_id']])->find();
        $list['product_name'] = $productname['name'];
        $list['factory_title'] = $factory['title'];
        $this->success('',$list);
    }

    /**
     * @return void
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * 获取渠道列表
     */
    public function channelList(){
        $list = Db::name("channel")->where('deletetime',null)->order("id desc")->select();
        $this->success('',$list);
    }

    /**
     * @return void
     * 工单提交
     */
        public function workAdd(){
        $product_id = $this->request->post("product_id");//产品ID
        $user_content = $this->request->post("user_content");//用户说明
        $remarks = $this->request->post("remarks");//备注
        $channel_id = $this->request->post("channel_id");//渠道ID
        $order_image = $this->request->post("order_image");//订单图
        $shop_name = $this->request->post("shop_name");//
        $order_code = $this->request->post("order_code");//
        $image = $this->request->post("image");//图
        $address_id = $this->request->post("address_id");//地址ID
        $real_pay_time = $this->request->post("real_pay_time");//地址ID
            if(!$product_id || !$channel_id || !$order_image || !$address_id || !$channel_id){
                $this->error("缺少必传参数");
            }
         if($address_id){
             $address_data =  Db::name("address")->where(['id'=>$address_id])->find();
             if(!$address_data){
                 $this->error("地址有误");
             }
             $add_data['address_id'] = $address_id;
             $add_data['res_mobile'] = $address_data['mobile'];
             $add_data['res_receiver'] = $address_data['receiver'];
             $add_data['res_address'] = $address_data['address'];
         }

        $product_data = Db::name("product")->where(['id'=>$product_id])->find();
         if(!$product_data){
             $this->error("数据有误");
         }
        $add_data['product_id'] = $product_id;
        $add_data['productname_id'] = $product_data['productname_id'];
        $add_data['factory_id'] = $product_data['factory_id'];
        $add_data['user_content'] = $user_content;
        $add_data['remarks'] = $remarks;
        $add_data['channel_id'] = $channel_id;
        $add_data['order_image'] = $order_image;
        $add_data['shop_name'] = $shop_name;
        $add_data['order_code'] = $order_code;
        $add_data['image'] = $image;
            $up_work_data = Db::name("work")->where(['productname_id'=>$product_data['productname_id'],'res_mobile'=>$add_data['res_mobile']])->find();
            if($up_work_data){
                $add_data['is_two'] = 1;
            }
            if($add_data['res_mobile']){
                $fan_data = Db::name("work")->where(['productname_id'=>$product_data['productname_id'],'res_mobile'=>$add_data['res_mobile']])->order('id desc')->find();
                if($fan_data){
                    $add_data['fan_time'] = time()-$fan_data['createtime'];
                }else{
                    $add_data['fan_time'] = 0;
                }

            }
        if($real_pay_time){
            $add_data['real_pay_time'] = date('Y-m-d H:i:s',$real_pay_time);
        }

        $add_data['createtime'] = time();
        $add_data['user_id'] = $this->auth->id;

        $in_status = Db::name("work")->insertGetId($add_data);
        Db::name("user")->where(['id'=>$this->auth->id])->setInc("work_sum");
        if($in_status){
            $log_content = "工单".$product_data['name']."待审核";
            \app\common\model\User::workLog($in_status,$log_content,$add_data);
            \app\admin\model\User::usernews($this->auth->id,"工单提交成功通知","您提交的工单“".$product_data['name']."”已提交成功，可在工单列表中查看。",$in_status);
            $this->success("成功");
        }else{
            $this->error("失败");
        }
    }
    public function workEdit(){
        $product_id = $this->request->post("product_id");//产品ID
        $user_content = $this->request->post("user_content");//用户说明
        $remarks = $this->request->post("remarks");//备注
        $channel_id = $this->request->post("channel_id");//渠道ID
        $order_image = $this->request->post("order_image");//订单图
        $shop_name = $this->request->post("shop_name");//
        $order_code = $this->request->post("order_code");//
        $image = $this->request->post("image");//图
        $address_id = $this->request->post("address_id");//地址ID
        $real_pay_time = $this->request->post("real_pay_time");//地址ID
        $id = $this->request->post("id");//地址ID
        if(!$product_id || !$channel_id || !$order_image || !$address_id || !$channel_id){
            $this->error("缺少必传参数");
        }
        if($address_id){
            $address_data =  Db::name("address")->where(['id'=>$address_id])->find();
            if(!$address_data){
                $this->error("地址有误");
            }
            $add_data['address_id'] = $address_id;
            $add_data['res_mobile'] = $address_data['mobile'];
            $add_data['res_receiver'] = $address_data['receiver'];
            $add_data['res_address'] = $address_data['address'];
        }

        $product_data = Db::name("product")->where(['id'=>$product_id])->find();
        if(!$product_data){
            $this->error("数据有误");
        }
        $add_data['product_id'] = $product_id;;
        $add_data['factory_id'] = $product_data['factory_id'];
        $add_data['user_content'] = $user_content;
        $add_data['remarks'] = $remarks;
        $add_data['channel_id'] = $channel_id;
        $add_data['order_image'] = $order_image;
        $add_data['shop_name'] = $shop_name;
        $add_data['order_code'] = $order_code;
        $add_data['image'] = $image;
        $up_work_data = Db::name("work")->where(['product_id'=>$product_id,'res_mobile'=>$add_data['res_mobile']])->find();
        if($up_work_data){
            $add_data['is_two'] = 1;
        }
        if($add_data['res_mobile']){
            $fan_data = Db::name("work")->where(['product_id'=>$product_id,'res_mobile'=>$add_data['res_mobile']])->order('id desc')->find();
            if($fan_data){
                $add_data['fan_time'] = time()-$fan_data['createtime'];
            }else{
                $add_data['fan_time'] = 0;
            }

        }
        $add_data['status'] = 1;
        if($real_pay_time){
            $add_data['real_pay_time'] = date('Y-m-d H:i:s',$real_pay_time);
        }
        $add_data['createtime'] = time();
        $add_data['user_id'] = $this->auth->id;
        $data = Db::name("work")->where(['id'=>$id,'user_id'=>$this->auth->id,'status'=>2])->find();
        if(!$data){
            $this->error("数据有误");
        }
        $in_status = Db::name("work")->where(['id'=>$id,'user_id'=>$this->auth->id])->update($add_data);
        Db::name("user")->where(['id'=>$this->auth->id])->setInc("work_sum");
        if($in_status){
            $log_content = "工单".$product_data['name']."待审核";
            \app\common\model\User::workLog($in_status,$log_content,$add_data);
            \app\admin\model\User::usernews($this->auth->id,"工单提交成功通知","您提交的工单“".$product_data['name']."”已提交成功，可在工单列表中查看。",$in_status);
            $this->success("成功");
        }else{
            $this->error("失败");
        }
    }
    /**
     * @return void
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * 工单列表
     */
    public function workList(){
            $user = $this->auth->getUser();

            $page = $this->request->post("page",1);
            $time = $this->request->post("time");//一周 week ，一月 month 三月 three_month

            $product_name = $this->request->post("product_name");
            $status = $this->request->post("status");//1待审核2已驳回3待用户寄出4待工厂收货5工厂检测中6待确认检查结果7待上传凭证8凭证待审核9待工厂寄出10已完成'

            $per_page = $this->request->post("per_page",15);
            $map['w.id'] = ['>',0];
            if($time){
                if($time == 'week'){
                    $startDate = strtotime('-1 week');
                }elseif ($time == 'month'){
                    $startDate = strtotime('-1 month');
                }else{
                    $startDate = strtotime('-3 month');
                }

                $endDate = time();
                $map['w.createtime'] = ['between', [$startDate, $endDate]];
            }
            if($product_name){
                $map['p.name'] = ['like', '%' . $product_name . '%'];
            }
            if($status){
                if($status == 5){
                    $map['w.status'] = ['in','5,6'];
                }else{
                    $map['w.status'] = $status;
                }

            }
            //$map['w.user_id'] = $user->id;

            $total = Db::name("work")->alias("w")->join("product p","p.id = w.product_id")
                ->where($map)->count();
            $str_num = ($page-1)*$per_page;
            $list = Db::name("work")->alias("w")
                ->field("w.id,w.product_id,w.createtime,w.status")
                ->join("product p","p.id = w.product_id")
                ->where($map)
                ->where('(w.user_id = '.$user->id.' or w.res_mobile = '.$user->mobile.')')
                ->order("w.id desc")
                ->limit($str_num,$per_page)
                ->select();
            if($list){
                foreach ($list as $k=>$v){
                    $list[$k]['createtime'] = date('Y-m-d H:i',$v['createtime']);
                    $product = Db::name("product")->where(['id'=>$v['product_id']])->find();
                    $list[$k]['product_name'] = $product['name'];
                    $list[$k]['product_code'] = $product['code'];
                    if($v['status'] == 6){
                        $list[$k]['status'] = 5;
                    }
                }
            }
            $re_data['list'] = $list;
            $re_data['last_page'] = $page;
            $re_data['total'] = $total;
            $re_data['per_page'] = $per_page;
            $this->success('获取成功', $re_data);
    }

    /**
     * @return void
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \think\exception\PDOException
     * 用户添加物流
     */
    public function worUserShipper(){
        $user = $this->auth->getUser();
        $type = $this->request->post("type");//1上传物流，2上传费用凭证
        $user_shipper_id = $this->request->post("user_shipper_id");
        $id = $this->request->post("id");
        $voucher = $this->request->post("voucher");
        $user_shipper_code = $this->request->post("user_shipper_code");
        $work_data = Db::name("work")->where(['id'=>$id])->find();
        if(!$work_data){
            $this->error("数据有误");
        }
        $product_data = Db::name("product")->where(['id'=>$work_data['product_id']])->find();
        if(!$product_data){
            $this->error("数据有误");
        }
        if($type == 1){
            if(!$id || !$user_shipper_code){
                $this->error("缺少必传参数");
            }
            $up_data['user_shipper_code'] = $user_shipper_code;
            $up_data['user_shipper_id'] = $user_shipper_id;
            $up_data['user_shipper_name'] = Db::name("shipper")->where(['id'=>$user_shipper_id])->value("name");
            $up_data['status'] = 4;
            $up_data['usersend_time'] = time();
            $title = '工单状态变更通知';
            $content = "您提交的工单“".$product_data['name']."”上传物流成功,正在等待厂家收货。";
            $admincontent = "工单“".$product_data['name']."”上传物流成功,正在等待厂家收货。";
            $shipper_data = Db::name("shipper")->where(['id'=>$user_shipper_id])->find();
            $log_content = "用户寄出 ".$shipper_data['name'].":".$user_shipper_code;

        }elseif ($type == 2){
            if(!$id || !$voucher){
                $this->error("缺少必传参数");
            }
            $up_data['voucher'] = $voucher;
            $up_data['status'] = 8;
            $up_data['voucher_time'] = time();
            $title = '工单状态变更通知';
            $content = "您提交的工单“".$product_data['name']."”上传费用凭证成功。";
            $admincontent = "工单“".$product_data['name']."”上传费用凭证成功。";
            $log_content = "用户上传凭证，待审核 ";

        }

        $work_data = Db::name("work")->where(['id'=>$id])->find();
        if($work_data){
            if(!$work_data['user_id']){
                $up_data['user_id'] = $user->id;
            }

            $up_status = Db::name("work")->where(['id'=>$id])->update($up_data);
            if($up_status){

                \app\admin\model\User::usernews($user->id,$title,$content,$id);
                if($work_data['admin_id']){
                    \app\admin\model\User::adminnews($work_data['admin_id'],$title,$admincontent,$id);
                }
                \app\common\model\User::workLog($id,$log_content,$work_data);
                $this->success("成功");
            }else{
                $this->error("失败");
            }
        }else{
            $this->error("数据有误");
        }
    }
    public function workDetails(){
        $user = $this->auth->getUser();
        $id = $this->request->post("id");
        if(!$id){
            $this->error("缺少必传参数");
        }
        $work_data = Db::name("work")->where(['id'=>$id])->find();
        if($work_data){
            $where['w.id'] = $id;
           // $where['w.user_id'] = $user->id;
            $list = Db::name("work")->alias('w')
                ->field("w.*,p.code as product_code,p.name as product_name")
                ->join("product p",'w.product_id = p.id')
                ->where($where)
                ->find();
            //$result = array("row" => $list);
            $product = Db::name("product")->where(['id'=>$list['product_id']])->where('deletetime',null)->find();
            $where_r['id'] = $product['factory_id'];
            $factory = Db::name("factory")->where($where_r)->where('deletetime',null)->find();
            //echo Db::name("factory")->getLastSql();
            $list['factory_tile'] = $factory['title'];
            $list['factory_name'] = $factory['name'];
            $list['factory_phone'] = $factory['phone'];
            $list['factory_address'] = $factory['address'];
            $user_content = $list['user_content'];
            $user_content = str_replace("<p>", "", $user_content);
            $user_content = str_replace("<br>", "", $user_content);
            $user_content = str_replace("</p>", "", $user_content);
            $list['user_content'] = $user_content;

            $admin = Db::name("admin")->where(['id'=>$list['admin_id']])->find();
            $list['admin_username'] = $admin['username'];
            $channel = Db::name("channel")->where(['id'=>$list['channel_id']])->find();
            $problem_arr = Db::name("problem")->where('id','in',$list['problem'])->select();
            $repair_arr = Db::name("repair")->where('id','in',$list['factory_status'])->select();
            $problem = '';
            if($problem_arr){
                foreach ($problem_arr as $k=>$v){
                    $problem .= $v['name'].',';
                }

            }
            $list['problem'] = trim($problem,',');

            $factory_status = '';
            if($repair_arr){
                foreach ($repair_arr as $k=>$v){
                    $factory_status .= $v['name'].',';
                }

            }
            $list['factory_status'] = trim($factory_status,',');

            $list['channel_name'] = $channel['name'];

            $user_shipper_data = Db::name("shipper")->where(['id'=>$list['user_shipper_id']])->find();
            $admin_shipper_data = Db::name("shipper")->where(['id'=>$list['admin_shipper_id']])->find();
            $list['user_shipper_name'] = $user_shipper_data['name'];
            $list['admin_shipper_name'] = $admin_shipper_data['name'];
            if($list['damage_reason'] == 1){
                $list['damage_reason'] = "非质量问题";
            }else{
                $list['damage_reason'] = "质量问题";
            }
            $sales_image = Db::name("config")->where(['name'=>'sales_image'])->value("value");
            $list['sales_image'] = $sales_image;

            $this->success('',$list);
        }else{
            $this->error("数据有误");
        }
    }

    /**
     * @return void
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * 物流公司
     */
    public function shipperList(){
        $list = Db::name("shipper")->select();
        $this->success("",$list);
    }
    public function getNotice(){
        $gonggao = Db::name("config")->where(['name'=>'gonggao'])->value("value");
        $list['notice'] = $gonggao;

        $this->success('公告信息',$list);
    }
}
